package controllers;

import helpers.GeneralHelper;
import helpers.LanguageHelper;
import helpers.StringHelper;
import helpers.ValidateHelper;

import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.cache.Cache;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.CategoryModel;

import quercus.CompileScriptEngine;
import systems.Recently;
import systems.RecentlyTag;

import entities.ApplicationConfig;
import entities.Article;
import entities.Category;
import entities.User;
import forms.CaptchaForm;


public class ContactServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		ApplicationConfig appConfig = (ApplicationConfig) request.getAttribute("sysConfig");
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		TreeMap<String, String> values = new TreeMap<String, String>();
		
		request.setAttribute("check", check);
		request.setAttribute("values", values);
		try {
			request.getRequestDispatcher("/templates/" + appConfig.getTemplateId() + "/pages/contact.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		ApplicationConfig appConfig = (ApplicationConfig) request.getAttribute("sysConfig");
		
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		TreeMap<String, String> values = new TreeMap<String, String>();
		
		TreeMap<String, Object> form = checkValid(request, check);
		check = (TreeMap<String, String>) form.get("checkValid");
		values = (TreeMap<String, String>) form.get("values");
		
		check = (TreeMap) CaptchaForm.checkValid(request, check);
		
		if (check.size() == 0) {
			try {
				Properties props = new Properties();
		        Session session = Session.getDefaultInstance(props, null);
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress(appConfig.getEmailAdmin(), (String) values.get("email")));
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
                		appConfig.getEmailAdmin(), (String) values.get("email")));
                msg.setSubject("Mail contact from " + (String) values.get("name"));
                msg.setText((String) values.get("content"));
                Transport.send(msg);

	        } catch (AddressException e) {
	                // ...
	        } catch (MessagingException e) {
	                // ...
	        }
			
			request.setAttribute("success", "Thanks for your contact.");
		}
		
		
		request.setAttribute("check", check);
		request.setAttribute("values", values);
		try {
			request.getRequestDispatcher("/templates/" + appConfig.getTemplateId() + "/pages/contact.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
		
	}
	
	private TreeMap<String, Object> checkValid(HttpServletRequest request, TreeMap check) {
		TreeMap<String, Object> form = new TreeMap<String, Object>();
		TreeMap<String, String> values = new TreeMap<String, String>();
		
		LanguageHelper translate = (LanguageHelper) request.getAttribute("translate");
		
		String name = (String) request.getParameter("name");
		String email = (String) request.getParameter("email");
		String title = (String) request.getParameter("title");
		String content = (String) request.getParameter("content");
		
		if (name == null || name.isEmpty()) {
			check.put("name", "Name is not empty.");
			values.put("name", "");
		} else {
			values.put("name", name);
		}
		
		if (email == null || email.isEmpty()) {
			check.put("email", "Email is not empty.");
			values.put("email", email);
		} else {
		    if (!ValidateHelper.isEmail(email)) {
		    	check.put("email", "Email is not valid.");
		    }
		    values.put("email", email);
		}
		
		if (title == null || title.isEmpty()) {
			check.put("title", "Title is not empty.");
			values.put("title", "");
		} else {
			values.put("title", title);
		}
		
		if (content == null || content.isEmpty()) {
			check.put("content", "Content is not empty.");
			values.put("content", "");
		} else {
			values.put("content", content);
		}
		
		form.put("checkValid", check);
		form.put("values", values);
		return form;
	}
}
